﻿using System;
using System.Collections.Generic;
using System.Resources;
using System.IO;
using System.Text;
using System.Xml;

namespace Localization.Repository
{
    class AndroidResourceWriter : IResourceWriter
    {
        private Dictionary<string, string> resources = new Dictionary<string, string>();
        private Stream ioStream = null;
        private string file;

        public AndroidResourceWriter() { }
        public AndroidResourceWriter(string fileName)
        {
            file = fileName;
        }
        public AndroidResourceWriter(Stream stream)
        {
            ioStream = stream;
        }

        public void AddResource(string name, byte[] value)
        {
            throw new NotImplementedException("Android resources only support string values.");
        }

        public void AddResource(string name, object value)
        {
            throw new NotImplementedException("Android resources only support string values.");
        }

        public void AddResource(string name, string value)
        {
            resources.Add(name, value);
        }

        public void Close()
        {

        }

        public void Generate()
        {
            if (ioStream == null)
                ioStream = File.Create(file);

            using (StreamWriter writer = new StreamWriter(ioStream))
            {
                try
                {
                    writer.WriteLine("<resources>");
                    foreach (KeyValuePair<string, string> item in resources)
                    {
                        // TODO: fix xml encoding for resource file
                        writer.WriteLine(
                            string.Format("<string name=\"{0}\">{1}</string>", item.Key, item.Value));
                    }
                    writer.WriteLine("</resouces>");
                    //writer.WriteStartElement("resources");

                    //foreach (KeyValuePair<string, string> item in resources)
                    //{
                    //    writer.WriteStartElement("string");
                    //    writer.WriteAttributeString("name", item.Key);
                    //    writer.
                    //}

                    //writer.WriteEndElement();
                }
                finally
                {
                    if (ioStream != null)
                        ioStream.Close();
                }
            }
        }

        public void Dispose()
        {
            resources = null;
        }
    }
}
